package com.geek.zeus.demos.web.mq.config;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: geek
 * @Date: 2025/10/11/17:21
 * @Description:
 */
/**
 * RabbitMQ配置类
 * 用于配置RabbitMQ监听器容器工厂
 */
@Configuration
public class RabbitmqConfig {

    @Value("${spring.rabbitmq.host:localhost}")
    private String host;

    @Value("${spring.rabbitmq.port:5672}")
    private int port;

    @Value("${spring.rabbitmq.username:guest}")
    private String username;

    @Value("${spring.rabbitmq.password:guest}")
    private String password;

    @Value("${spring.rabbitmq.virtual-host:/}")
    private String virtualHost;

    /**
     * 配置连接工厂，增加连接参数优化
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);

        // 优化连接参数
        connectionFactory.setConnectionTimeout(10000); // 10秒连接超时
        connectionFactory.setRequestedHeartBeat(30);   // 30秒心跳

        // 连接池配置
        connectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CONNECTION);
        connectionFactory.setConnectionCacheSize(5);
        connectionFactory.setChannelCacheSize(10);

        return connectionFactory;
    }

    /**
     * 创建SimpleRabbitListenerContainerFactory实例
     * 用于配置RabbitMQ消息监听器的基本参数
     *
     * @param connectionFactory 连接工厂，用于建立与RabbitMQ服务器的连接
     * @return 配置好的SimpleRabbitListenerContainerFactory实例
     */
    @Bean(name="qos_4")
    public SimpleRabbitListenerContainerFactory getSimpleRabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        // 设置最大并发消费者数量为4
        factory.setMaxConcurrentConsumers(4);
        // 设置连接工厂
        factory.setConnectionFactory(connectionFactory);
        // 设置手动确认模式，需要手动确认消息消费成功工程院

        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }
}

